package cn.dgut.FrontLogin;


import cn.dgut.Entity.LoginFlag;
import cn.dgut.Entity.UserInfo;
import cn.dgut.Utils.JDBCUtils;
import cn.dgut.Utils.httpClientTool;
import org.apache.http.message.BasicNameValuePair;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * loginServlet是用来验证莞工中央登录的
 * 用来请求open_id和用户信息，并储存isLogin(session)中
 */

@WebServlet("/login/dgut")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String token = request.getParameter("token");
        String appid = "javaee";
        String appsecret = "b3b52e43ccfd";
        String userip = request.getRemoteAddr();     //获取本地ip

        String url = "https://cas.dgut.edu.cn/ssoapi/v2/checkToken";
        // 创建checkToken的参数列表
        List<BasicNameValuePair> paramList = new ArrayList<>();
        paramList.add(new BasicNameValuePair("token",token));
        paramList.add(new BasicNameValuePair("appid",appid));
        paramList.add(new BasicNameValuePair("appsecret",appsecret));
        paramList.add(new BasicNameValuePair("userip",userip));

        //封装了一个httpClient工具类
        httpClientTool client = new httpClientTool();
        String resultString = client.getPostInfo(url,paramList,response);
        Jsonb jsonb = JsonbBuilder.create();
        LoginFlag loginFlag = jsonb.fromJson(resultString,LoginFlag.class);
        if(Integer.parseInt(loginFlag.getError())!=0){
            //token不合法，退出
            response.getWriter().println(resultString);
            return;
        }else {
            String access_token = loginFlag.getAccess_token();
            String openid = loginFlag.getOpenid();
            url = "https://cas.dgut.edu.cn/oauth/getUserInfo";
            // 创建getUserInfo的参数列表
            paramList = new ArrayList<>();
            paramList.add(new BasicNameValuePair("access_token", access_token));
            paramList.add(new BasicNameValuePair("openid", openid));
            resultString = client.getPostInfo(url, paramList, response);
            UserInfo user = jsonb.fromJson(resultString, UserInfo.class);

            if(user.getError()!=null){
                //access-token不合法，退出
                response.getWriter().println(resultString);
                return;
            }

            String id=null;
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;
            try {
                 //1.获取连接
                 conn = JDBCUtils.getConnection();
                 //开启事务
                 conn.setAutoCommit(false);
                 stmt = conn.createStatement();//获取执行sql对象
                 String sql = "select * from Student where student_name = '"+user.getName()+"'";
                 rs = stmt.executeQuery(sql);
                 while (rs.next()){
                     id = String.valueOf(rs.getInt("student_id"));
                 }
                 if(id==null){
                     sql = "INSERT INTO `Student` VALUES (null,'"+user.getName()+"','123456','null','null','default.png','no','null')";
                     stmt.executeUpdate(sql);
                     sql = "select * from Student where student_name = '"+user.getName()+"'";
                     rs = stmt.executeQuery(sql);
                     while (rs.next()){
                         id = String.valueOf(rs.getInt("student_id"));
                     }
                 }
                //提交事务
                conn.commit();
            } catch (Exception e) {
                //事务回滚
                try {
                    if(conn != null) {
                        conn.rollback();
                    }
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }finally {
                JDBCUtils.close(rs,stmt,conn);
            }

            Map<String, String> info = new HashMap<String, String>();
            info.put("name", user.getName());
            info.put("id",id);
            HttpSession session = request.getSession(true);
            session.setAttribute("isFrontLogin", info);
            response.sendRedirect("/index.jsp");
        }
    }
}
